package com.example.service;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.AirspaceUtilization;
import com.example.entity.info.*;
import com.example.mapper.AirspaceUtilizationMapper;
import com.example.entity.transAirspaceUtilization;
import com.example.mapper.UtiPubRecordMapper;
import com.example.mapper.UtiPubUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AirspaceUtilizationService {

    @Autowired
    private AirspaceUtilizationMapper airspaceUtilizationMapper;
    @Autowired
    private UtiPubUserMapper utiPubUserMapper;
    @Autowired
    private UtiPubRecordMapper utiPubRecordMapper;

    //关键词搜索和排序
    public List<transAirspaceUtilization> keywordSearch(String keyword, String sort, boolean order) {
        QueryWrapper<AirspaceUtilization> wrapper = new QueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            // 模糊匹配 program_name、application_acceptance_time 和 id 字段
            wrapper.like("file_name", keyword)
                    .or()
                    .like("publishing_time", keyword) // 假设 publishing_time 被格式化为字符串
                    .or()
                    .like("id", keyword);
        }

        if (sort != null && !sort.isEmpty()) {
            if (order) {
                wrapper.orderByAsc(sort);
            } else {
                wrapper.orderByDesc(sort);
            }
        }

        List<AirspaceUtilization> airspaceUtilizations = airspaceUtilizationMapper.selectList(wrapper);
        return airspaceUtilizations.stream().map(airspaceUtilization -> {
            transAirspaceUtilization transresult = new transAirspaceUtilization();
            BeanUtils.copyProperties(airspaceUtilization, transresult);
            String landingzone = airspaceUtilization.getTakeoffLandInfo();
            String airlane = airspaceUtilization.getAirLaneInfo();
            String work = airspaceUtilization.getWorkInfo();
            String special = airspaceUtilization.getSpecialInfo();
            if (landingzone != null && !landingzone.isEmpty()) {
                JSONArray jsonArray = JSONArray.parseArray(landingzone);
                List<TakeoffLandInfo> landingZoneInfos = jsonArray.toJavaList(TakeoffLandInfo.class);
                transresult.setTakeoffLandInfo(landingZoneInfos);
            }

            if (airlane != null && !airlane.isEmpty()) {
                JSONArray jsonArray = JSONArray.parseArray(airlane);
                List<AirLaneInfo> airLaneInfos = jsonArray.toJavaList(AirLaneInfo.class);
                transresult.setAirlineInfo(airLaneInfos);
            }
            if (work != null && !work.isEmpty()) {
                JSONArray jsonArray = JSONArray.parseArray(work);
                List<WorkInfo> workInfos = jsonArray.toJavaList(WorkInfo.class);
                transresult.setWorkInfo(workInfos);
            }
            if (special != null && !special.isEmpty()) {
                JSONArray jsonArray = JSONArray.parseArray(special);
                List<SpecialInfo> speciaInfos = jsonArray.toJavaList(SpecialInfo.class);
                transresult.setSpecialInfo(speciaInfos);
            }
            return transresult;
        }).collect(Collectors.toList());
    }

    //获取发布对象信息
    public List<UtiPubUser> getUtiPubUser() {
        return utiPubUserMapper.selectList(null);
    }

    // 添加新的发布用户
    public List<UtiPubUser> saveNameAndReturnAll(String name) {
        UtiPubUser entity = new UtiPubUser();
        entity.setPublishingUser(name);
        utiPubUserMapper.insert(entity); // 插入新记录
        // 查询并返回所有用户
        return utiPubUserMapper.selectList(null);
    }

    //记录发布用户信息并实时更新
    @Transactional // 添加事务管理，保证并发安全
    public Map<Integer, List<UtiPubRecord>> saveOrUpdateUserPublishRecord(int instructionId, String userName) {
        UtiPubRecord record = new UtiPubRecord();
        record.setInstructionId(instructionId);
        record.setPublishingUser(userName);

        // 保存到数据库的时间格式为 'yyyy-MM-dd HH:mm:ss'
        String dbTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        record.setPublishingTime(dbTimeFormat);

        // 检查是否存在相同的 publishing_user 和 instruction_id
        QueryWrapper<UtiPubRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("publishing_user", userName)
                .eq("instruction_id", instructionId);

        UtiPubRecord existingRecord = utiPubRecordMapper.selectOne(queryWrapper);

        if (existingRecord != null) {
            // 更新现有记录的 publishing_time
            existingRecord.setPublishingTime(dbTimeFormat);
            utiPubRecordMapper.updateById(existingRecord);
        } else {
            // 查询当前 instructionId 下最大的 internal_id
            QueryWrapper<UtiPubRecord> internalIdQuery = new QueryWrapper<>();
            internalIdQuery.eq("instruction_id", instructionId)
                    .orderByDesc("internal_id")
                    .last("LIMIT 1");

            UtiPubRecord maxRecord = utiPubRecordMapper.selectOne(internalIdQuery);
            int nextInternalId = (maxRecord != null) ? maxRecord.getInternalId() + 1 : 1;

            // 设置新的 internal_id
            record.setInternalId(nextInternalId);

            // 插入新记录
            utiPubRecordMapper.insert(record);
        }

        // 获取所有用户发布记录
        List<UtiPubRecord> allRecords = utiPubRecordMapper.selectList(null);

        // 在返回给前端前，将 publishingTime 格式转换为 'yy/M/d HH:mm:ss'
        SimpleDateFormat frontendFormat = new SimpleDateFormat("yy/M/d HH:mm:ss");
        for (UtiPubRecord rec : allRecords) {
            try {
                Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(rec.getPublishingTime());
                rec.setPublishingTime(frontendFormat.format(date));
            } catch (ParseException e) {
                // 处理解析错误
                e.printStackTrace();
            }
        }

        // 按 instructionId 分组返回
        return allRecords.stream().collect(Collectors.groupingBy(UtiPubRecord::getInstructionId));
    }



    //根据需求说明id返回历史信息记录
    public List<UtiPubRecord> getRecordsByInstructionIdWithSorting(Integer instructionId, boolean order) {
        QueryWrapper<UtiPubRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("instruction_id", instructionId);

        // 根据 asc 参数进行排序
        if (order) {
            queryWrapper.orderByAsc("publishing_time");
        } else {
            queryWrapper.orderByDesc("publishing_time");
        }

        return utiPubRecordMapper.selectList(queryWrapper);
    }

}


//    备份
//    @Transactional // 添加事务管理，保证并发安全
//    public Map<Integer, List<UtiPubRecord>> saveOrUpdateUserPublishRecord(int instructionId, String userName) {
//        UtiPubRecord record = new UtiPubRecord();
//        record.setInstructionId(instructionId);
//        record.setPublishingUser(userName);
//
//        // 获取当前时间并转换为字符串格式
//        // 获取当前时间并转换为字符串格式
////        String currentTime = new SimpleDateFormat("yy M/d HH:mm:ss").format(new Date());
////        record.setPublishingTime(currentTime);
//
//        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//        record.setPublishingTime(currentTime);
//
//        // 检查是否存在相同的 publishing_user 和 instruction_id
//        QueryWrapper<UtiPubRecord> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("publishing_user", userName)
//                .eq("instruction_id", instructionId);
//
//        UtiPubRecord existingRecord = utiPubRecordMapper.selectOne(queryWrapper);
//
//        if (existingRecord != null) {
//            // 更新现有记录的 publishing_time
//            existingRecord.setPublishingTime(currentTime);
//            utiPubRecordMapper.updateById(existingRecord);
//        } else {
//            // 查询当前 instructionId 下最大的 internal_id
//            QueryWrapper<UtiPubRecord> internalIdQuery = new QueryWrapper<>();
//            internalIdQuery.eq("instruction_id", instructionId)
//                    .orderByDesc("internal_id")
//                    .last("LIMIT 1");
//
//            UtiPubRecord maxRecord = utiPubRecordMapper.selectOne(internalIdQuery);
//            int nextInternalId = (maxRecord != null) ? maxRecord.getInternalId() + 1 : 1;
//
//            // 设置新的 internal_id
//            record.setInternalId(nextInternalId);
//
//            // 插入新记录
//            utiPubRecordMapper.insert(record);
//        }
//
//        // 获取所有用户发布记录并按 instructionId 分组
//        List<UtiPubRecord> allRecords = utiPubRecordMapper.selectList(null);
//        return allRecords.stream().collect(Collectors.groupingBy(UtiPubRecord::getInstructionId));
//    }
